package com.igeek.health.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.igeek.health.constant.MessageConstant;
import com.igeek.health.constant.RedisMessageConstant;
import com.igeek.health.entity.Member;
import com.igeek.health.result.Result;
import com.igeek.health.service.IMemberService;
import com.igeek.health.vo.LoginQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/9/13  9:48
 */
@RestController
@RequestMapping("/app/member")
@Api(tags = "会员模块的控制层")
@CrossOrigin //处理跨越问题
public class MemberController {

    @Autowired
    private IMemberService memberService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/login")
    @ApiOperation("快速登录")
    public Result login(@RequestBody LoginQueryVO loginQueryVO){
        //1.获取redis中的验证码 进行比对
        String code = loginQueryVO.getValidateCode();
        String telephone = loginQueryVO.getTelephone();

        String codeInRedis =
                stringRedisTemplate.opsForValue().get(telephone + "_" + RedisMessageConstant.SENDTYPE_LOGIN + "_" + code);
        if(StrUtil.isEmpty(code) || StrUtil.isEmpty(telephone)){
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        if(StrUtil.isEmpty(codeInRedis) || !code.equals(codeInRedis)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //2.验证码正确后 执行登录业务 返回token数据
        String token = memberService.login(telephone);
        if(StrUtil.isNotEmpty(token)){
            return new Result(true,MessageConstant.LOGIN_SUCCESS,token);
        }
        return new Result(false,MessageConstant.LOGIN_FAIL);
    }

    //会员中心
    @GetMapping("")
    @ApiOperation("会员中心")
    public Result findOne(HttpServletRequest request){
        String memberId = request.getAttribute("memberId").toString();
        Member member = memberService.getById(memberId);
        if(ObjectUtil.isNotEmpty(member)){
            return new Result(true,MessageConstant.QUERY_MEMBER_SUCCESS,member);
        }
        return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
    }
    //修改个人头像
}
